package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class AdminManager {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private AdminService adminService;


    //生成验证码
    public LineCaptcha verification(String uuid) {

        LineCaptcha lineCaptcha = new LineCaptcha(200, 100);
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE + uuid, lineCaptcha.getCode(), Duration.ofMinutes(5));
        return lineCaptcha;

    }

    //登录
    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {

        String code = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        if (!StrUtil.equals(code, verificationCode)) {
            throw new BusinessException("验证码不正确");
        }

        String md5Pwd = SecureUtil.md5(password);

        Admin admin = adminService.findByUsernameAndPassword(username, md5Pwd);
        if (admin == null) {
            throw new BusinessException("用户名密码不正确");
        }

        admin.setPassword(null);
        Map<String, Object> claims = BeanUtil.beanToMap(admin);
        String token = JwtUtil.createToken(claims);
        String json = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));
        Map result = new HashMap();
        result.put("token", token);
        return ResponseEntity.ok(result);


    }
    //登录
    public Admin findBytoken(String token) {

        token = token.replace("Bearer ", "");

        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);

        if (StrUtil.isEmpty(json)) {
            return null;
        }
        Admin admin = JSON.parseObject(json, Admin.class);

        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));

        return admin;

    }
    //登出
    public void logout(String token) {

        token = token.replace("Bearer ", "");
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
    }
}
